from django.db import models
from datetime import datetime
from django.utils.encoding import force_unicode
from django.conf import settings
from simplestats import queries
from calendar import monthrange
from django.core.urlresolvers import reverse

query_map = getattr(queries, settings.DATABASE_ENGINE)

def dict_to_sparse(d, start=None, end=None):
    if end == None:
        end = max(d.keys())
    if start == None:
        start = min(d.keys())
    to_return = []
    for i in range(start, end):
        try:
            to_return.append(d[i])
        except KeyError:
            to_return.append(0)
    return to_return

class TimeManager(models.Manager):
    def by_hour(self, dt):
        from django.db import connection
        cursor = connection.cursor()
        query = query_map['hour'] % (dt.strftime("%Y-%m-%d"))
        cursor.execute(query)
        hours = dict([(int(row[1]), int(row[0])) for row in cursor.fetchall()])
        return dict_to_sparse(hours, start=0, end=24)

    def by_day(self, dt):
        from django.db import connection
        cursor = connection.cursor()
        query = query_map['day'] % (dt.strftime("%Y-%m"))
        cursor.execute(query)
        days = dict([(int(row[1])-1, int(row[0])) for row in cursor.fetchall()])
        return dict_to_sparse(days, start=0, end=monthrange(dt.year,dt.month)[1])

    def by_month(self, dt):
        from django.db import connection
        cursor = connection.cursor()
        query = query_map['month'] % (dt.strftime("%Y"))
        cursor.execute(query)
        months = dict([(int(row[1])-1, int(row[0])) for row in cursor.fetchall()])
        return dict_to_sparse(months, start=0, end=12)

    def by_year(self):
        from django.db import connection
        cursor = connection.cursor()
        query = query_map['day']
        cursor.execute(query)
        years = dict([(int(row[0]), int(row[1])) for row in cursor.fetchall()])
        return dict_to_sparse(months)

class PageView(models.Model):
    path = models.CharField(max_length = 2083)
    method = models.CharField(max_length = 4)
    remote_addr = models.IPAddressField()
    http_referrer = models.CharField(max_length = 2083, null=True)
    time = models.DateTimeField(default = datetime.now)
    
    objects = TimeManager()

    def __unicode__(self):
        return "%s %s %s %s %s" % (self.path, self.method, str(self.remote_addr), self.http_referrer, str(self.time))
    
    def get_absolute_url(self):
        return reverse('stat_object_detail', kwargs = {
            'year' : self.time.year,
            'month' : self.time.month,
            'day' : self.time.day,
            'object_id' : self.id,
        })
    
    class Admin:
        pass